<script>
    import {getContext, untrack} from 'svelte';
    import {observeResize, runReposition, toSeconds} from '#lib';
    import {getSlotTimeLimits} from './lib.js';
    import Days from './Days.svelte';

    let {_bodyEl, _bodyHeight, _bodyWidth, _bodyScrollLeft, _headerEl, _filteredEvents, _sidebarEl, _dayTimes, _dayTimeLimits,
        _recheckScrollable, _daysHs, _viewResources, _viewDates, scrollTime, slotDuration, slotWidth, theme} = getContext('state');

    let refs = [];

    function scrollToTime() {
        let slotTimeLimits = getSlotTimeLimits($_dayTimeLimits, $_viewDates[0]);
        $_bodyEl.scrollLeft = (toSeconds($scrollTime) - toSeconds(slotTimeLimits.min)) / toSeconds($slotDuration) * $slotWidth;
        $_bodyScrollLeft = $_bodyEl.scrollLeft;
    }
    $effect(() => {
        $_viewDates;
        $scrollTime;
        untrack(scrollToTime);
    });

    function reposition() {
        $_daysHs.clear();
        runReposition(refs, $_viewResources);
    }
    $effect(() => {
        $_filteredEvents;
        $_viewResources;
        untrack(reposition);
    });

    function onscroll() {
        $_headerEl.scrollLeft = $_bodyEl.scrollLeft;
        $_sidebarEl.scrollTop = $_bodyEl.scrollTop;
        $_bodyScrollLeft = $_bodyEl.scrollLeft;
    }

    function onresize() {
        $_bodyHeight = $_bodyEl.clientHeight;
        $_bodyWidth = $_bodyEl.clientWidth;
        $_recheckScrollable = true;
    }
</script>

<div
    bind:this={$_bodyEl}
    class="{$theme.body}"
    {onscroll}
    use:observeResize={onresize}
>
    <div class="{$theme.content}">
        <div class="{$theme.lines}">
            {#each $_viewDates as date}
                {#each $_dayTimes[date.getTime()] as time}
                    <div class="{$theme.line}{time[2] ? '' : ' ' + $theme.minor}"></div>
                {/each}
            {/each}
        </div>
        {#each $_viewResources as resource, i}
            <!-- svelte-ignore binding_property_non_reactive -->
            <Days {resource} bind:this={refs[i]}/>
        {/each}
    </div>
</div>

<svelte:window on:resize={reposition}/>
